<template>
  <div>
    <div class="header-form card-filter-box" style="margin: 20px 20px 12px 20px;padding-bottom:24px;">
      <FilterTool
        ref="FilterToolRef"
        v-model="paramsObj"
        :filter-list="filterList"
        show-search-btn
        @handelClick="queryClick"
        @queryEmpty="queryEmpty"
        @filterTagStatus="filterTagStatus"
      />
    </div>
    <div class="app-container mengli-all-order">
      <div style="margin-bottom:20px;display:flex;align-items:center;">
        <Title :is-show="true" :total="list.total" title="列表名称"/>
        <create-button
          v-if="hasRouteAuth('mengli:channelOrder:create') || isAdmin"
          :add-name="'新增'"
          is-own-logic
          width="96px"
          class="btn-right-item"
          @click="toCreate"/>
      </div>
      <div v-loading="listLoading" class="table-list" style="min-height: 100px;">
        <u-table
          v-if="list.items.length > 0"
          ref="allOrderTableRef"
          :data="list.items"
          :height="setTableHeight"
          :row-height="rowHeight()"
          :border="false"
          use-virtual
          class="table-fixed"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row>
          <!-- <u-table-column align="left" label="订单类型" width="120">
            <template slot-scope="scope">
              <div>{{ scope.row.orderType | mengliOrderStatus }}</div>
            </template>
          </u-table-column> -->
          <u-table-column align="left" label="订单编号" min-width="150">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.orderNum" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.orderNum }}</div>
                <router-link
                  :to="{name: 'mengliOrderDetail', params: { id: scope.row.id }, query: { type: 3 }}"
                  class="order-num"
                ><div class="ellipsis">{{ scope.row.orderNum }}</div></router-link>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="下单日期" min-width="110">
            <template slot-scope="scope">
              <div v-if="scope.row.orderTime">{{ scope.row.orderTime | standardFormat('YYYY/MM/DD') }}</div>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="客户名称" min-width="120">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.clientName" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.clientName }}</div>
                <div class="ellipsis">{{ scope.row.clientName }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="刊例价" width="80">
            <template slot-scope="scope">
              <div v-if="scope.row.articlesPrice || scope.row.articlesPrice === 0">{{ (scope.row.articlesPrice / 100) | moneyFilter }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="折扣" width="80">
            <template slot-scope="scope">
              <div v-if="scope.row.discountPrice || scope.row.discountPrice === 0">{{ (scope.row.discountPrice / 100) | moneyFilter }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="含税金额" width="80">
            <template slot-scope="scope">
              <div v-if="scope.row.taxAmount || scope.row.taxAmount === 0">{{ (scope.row.taxAmount / 100) | moneyFilter }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="渠道价" width="80">
            <template slot-scope="scope">
              <div v-if="scope.row.channelPrice || scope.row.channelPrice === 0">{{ (scope.row.channelPrice / 100) | moneyFilter }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="策划价" width="80">
            <template slot-scope="scope">
              <div v-if="scope.row.planPrice || scope.row.planPrice === 0">{{ (scope.row.planPrice / 100) | moneyFilter }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="收入类型" width="80">
            <template slot-scope="scope">
              {{ scope.row.incomeTypeStr || '--' }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="核销状态" width="100">
            <template slot-scope="scope">
              <div>{{ scope.row.accountState | setAccountState }}</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="账号" width="110">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.resourceName" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.resourceName }}</div>
                <div class="ellipsis">{{ scope.row.resourceName }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="账号归属" width="110">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.accountBelongName" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.accountBelongName }}</div>
                <div class="ellipsis">{{ scope.row.accountBelongName }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="ID" width="110">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.resourceCode" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.resourceCode }}</div>
                <div class="ellipsis">{{ scope.row.resourceCode }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="下单平台" width="110">
            <template slot-scope="scope">
              {{ scope.row.orderPlatform || '--' }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="所属机构" width="110">
            <template slot-scope="scope">
              {{ scope.row.organization || '--' }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="下单形式" width="110">
            <template slot-scope="scope">
              {{ scope.row.orderForm || '--' }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="IP形象" width="110">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.ipName" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.ipName }}</div>
                <div class="ellipsis">{{ scope.row.ipName }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="品牌名称" width="110" min-width="120">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.theme" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.theme }}</div>
                <div class="ellipsis">{{ scope.row.theme }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="文案内容" min-width="110">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.content" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.content }}</div>
                <div class="ellipsis">{{ scope.row.content }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="终端品牌" min-width="110">
            <template slot-scope="scope">
              {{ scope.row.terminalType || '--' }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="下单链接" min-width="120">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.orderLink" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.orderLink }}</div>
                <div class="ellipsis">{{ scope.row.orderLink }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="销售" min-width="110">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.market" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.market }}</div>
                <div class="ellipsis">{{ scope.row.market }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="所属部门" min-width="110">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.department" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.department }}</div>
                <div class="ellipsis">{{ scope.row.department }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="策划执行人" min-width="110">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.mastermind" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.mastermind }}</div>
                <div class="ellipsis">{{ scope.row.mastermind }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="备注" min-width="110">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.remark" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.remark }}</div>
                <div class="ellipsis">{{ scope.row.remark }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="业绩" width="80">
            <template slot-scope="scope">
              <div v-if="scope.row.performance || scope.row.performance === 0">{{ (scope.row.performance / 100) | moneyFilter }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="成本小计" width="80">
            <template slot-scope="scope">
              <div v-if="scope.row.cost || scope.row.cost === 0">{{ (scope.row.cost / 100) | moneyFilter }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="执行人" min-width="110">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.orderOperatorName" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.orderOperatorName }}</div>
                <div class="ellipsis">{{ scope.row.orderOperatorName }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="协作部门" min-width="110">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.cooperationDepartmentName" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.cooperationDepartmentName }}</div>
                <div class="ellipsis">{{ scope.row.cooperationDepartmentName }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="分成基数" min-width="80">
            <template slot-scope="scope">
              <div v-if="scope.row.priceBase || scope.row.priceBase === 0">{{ (scope.row.priceBase / 100) | moneyFilter }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="订单来源" min-width="110">
            <template slot-scope="scope">
              {{ scope.row.orderSource | orderSourceType }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="到账日期" min-width="110">
            <template slot-scope="scope">
              <div v-if="scope.row.arrivalDate">{{ scope.row.arrivalDate | standardFormat('YYYY/MM/DD') }}</div>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建日期" min-width="110">
            <template slot-scope="scope">
              <div v-if="scope.row.createTime">{{ scope.row.createTime | standardFormat('YYYY/MM/DD') }}</div>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" width="80" label="操作" fixed="right">
            <template slot-scope="scope">
              <el-dropdown trigger="click">
                <div class="el-dropdown-link" style="cursor:pointer;">
                  <img :src="setting" alt="操作">
                </div>
                <el-dropdown-menu slot="dropdown" style="margin-top:-24px;margin-right:15px;padding: 0;">
                  <el-dropdown-item style="width:100px;text-align: center" @click.native="toCheck(scope.row)">
                    <div>查看</div>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="hasRouteAuth('mengli:channelOrder:edit') || isAdmin" style="width:100px;text-align: center" @click.native="toEdit(scope.row)">
                    <div>编辑</div>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="hasRouteAuth('mengli:channelOrder:delete') || isAdmin" style="width:100px;text-align: center" @click.native="toDel(scope.row)">
                    <div>删除</div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </u-table-column>
        </u-table>
        <empty-placeholder v-else style="margin-bottom: 24px" />
      </div>
      <el-row type="flex" justify="end" class="pagination-area">
        <el-pagination
          v-show="list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          layout="total, prev, pager, next, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-row>
    </div>
  </div>
</template>
<script>
import setting from '@/assets/setting.png';
import FilterTool from '@/components/Tool/filter';
import Title from '@/components/Title';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import createButton from '@/components/CreateButton';
import { getmengliOrder, mengliOrderDel } from '@/api/mengli';
import { getDepartmentList, platformList, getIncomeType } from '@/api/select';
import { mengliOrderStatus, setAccountState } from '@/filters/status';
import { moneyFilter } from '@/filters/number';
import { standardFormat } from '@/filters/date';
import { verificationOptions } from '@/views/project/model/selectData';
import { hasRouteAuth } from '@/utils/permission';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { mapState } from 'vuex';
import TableAdaptive from '@/mixins/tableAdaptive';

export default {
  components: { FilterTool, Title, EmptyPlaceholder, createButton },
  filters: { mengliOrderStatus, moneyFilter, standardFormat, setAccountState,
    orderSourceType(type) {
      const obj = {
        1: '飞博招商',
        2: '达人个人引进'
      };
      return obj[String(type)] || '--';
    }
  },
  mixins: [TableAdaptive],
  data() {
    return {
      verificationOptions,
      setting,
      paramsObj: {},
      orderTypeOption: [
        { value: 0, label: '商务订单' },
        { value: 1, label: '营销授权' },
        { value: 2, label: '电商销售' },
        { value: 3, label: '渠道订单' }
      ],
      page: 1,
      perPage: 20,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInint: true
      },
      listLoading: false,
      attributionMatrixOptions: [],
      orderPlatformOption: [],
      incomeOptions: [],

      rangeKeyArr: [{
        attr: 'orderTime',
        start: 'orderStartTime',
        end: 'orderEndTime',
        type: 'time'
      }, {
        attr: 'arrivalTime',
        start: 'arrivalStartTime',
        end: 'arrivalEndTime',
        type: 'time'
      }, {
        attr: 'createTime',
        start: 'createStartTime',
        end: 'createEndTime',
        type: 'time'
      }],
      isUmyTable: true
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    filterList() {
      const arr = [
        // 输入框
        { keyword: 'orderNum', name: '订单编号', type: 'input' },
        { keyword: 'clientName', name: '客户名称', type: 'input' },
        { keyword: 'orderOperator', name: '执行人', type: 'input' },
        { keyword: 'resource', name: '账号', type: 'input' },
        { keyword: 'market', name: '销售', type: 'input' },
        { keyword: 'theme', name: '品牌名称', type: 'input' },
        { keyword: 'remark', name: '备注', type: 'input' },
        // 下拉
        { keyword: 'accountState', name: '核销状态', type: 'select', options: this.verificationOptions },
        { keyword: 'incomeType', name: '收入类型', type: 'select', options: this.incomeOptions },
        { keyword: 'departmentId', name: '所属部门', type: 'select', isSearch: true, options: this.attributionMatrixOptions },
        { keyword: 'orderPlatform', name: '下单平台', type: 'select', options: this.orderPlatformOption },
        // 日期
        {
          keyword: 'orderTime',
          name: '下单日期',
          timeType: 'daterange',
          type: 'rangeDate'
        },
        {
          keyword: 'arrivalTime',
          name: '到账日期',
          timeType: 'daterange',
          type: 'rangeDate'
        },
        {
          keyword: 'createTime',
          name: '创建日期',
          timeType: 'daterange',
          type: 'rangeDate'
        }
      ];
      return arr;
    }
  },
  created() {
    this.loadMore();
  },
  methods: {
    hasRouteAuth,
    loadMore() {
      this.getDepartment();
      this.platformList();
      this.incomeTypeList();
      this.fetchData(true);
    },
    getDepartment() {
      getDepartmentList({ type: 5 }).then(res => {
        if (res.data) {
          res.data.unshift({ value: -2, label: '--' });
          this.attributionMatrixOptions = res.data;
        }
      }).catch((err) => {
        console.error(err);
      });
    },
    // 下单平台
    async platformList() {
      try {
        const result = await platformList();
        result.data = result.data.map(item => {
          item = {
            value: item.id,
            label: item.value
          };
          return item;
        });
        this.orderPlatformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    // 获取收入类型的列表
    async incomeTypeList() {
      try {
        const result = await getIncomeType();
        if (result.data) {
          result.data.forEach(i => {
            i.value = i.id;
            i.label = i.name;
          });
          this.incomeOptions = result.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      // 时间处理
      /* if (params.orderTime && params.orderTime.length === 2) {
        params.orderStartTime = Math.round(params.orderTime[0] / 1000);
        params.orderEndTime = Math.round(params.orderTime[1] / 1000);
      }
      if (params.arrivalTime && params.arrivalTime.length === 2) {
        params.arrivalStartTime = Math.round(params.arrivalTime[0] / 1000);
        params.arrivalEndTime = Math.round(params.arrivalTime[1] / 1000);
      }
      if (params.createTime && params.createTime.length === 2) {
        params.createStartTime = Math.round(params.createTime[0] / 1000);
        params.createEndTime = Math.round(params.createTime[1] / 1000);
      }
      delete params.orderTime;
      delete params.arrivalTime;
      delete params.createTime; */
      paramsRangeFormat(this.rangeKeyArr, params);
      params.page = this.page;
      params.perPage = this.perPage;
      this.listLoading = true;
      getmengliOrder(params).then(({ data }) => {
        data.items.map(item => {
          if (item.cooperationDepartment && item.cooperationDepartment.length) {
            item.cooperationDepartmentName = item.cooperationDepartment.map(val => val.name).join(',');
          }
          if (item.ipAry && item.ipAry.length) {
            item.ipName = item.ipAry.map(val => {
              return `${val.ipFigure}/${val.ipSeries || '--'}`;
            }).join(',');
          }
          if (item.orderOperator && item.orderOperator.length) {
            item.orderOperatorName = item.orderOperator.map(val => val.userName).join(',');
          }
          return item;
        });
        this.list = data;
        this.list.isInit = false;
        this.listLoading = false;
        this.page = data.page;
        this.perPage = data.perPage;
      }).catch(e => {
        console.error(e);
      });
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    toCreate() {
      this.$router.push({
        name: 'mengliOrderAdd',
        query: { type: 3 }
      });
    },
    toCheck(row) {
      this.$router.push({
        name: 'mengliOrderDetail',
        params: { id: row.id },
        query: { type: 3 }
      });
    },
    toEdit(row) {
      this.$router.push({
        name: 'mengliOrderEdit',
        params: { id: row.id },
        query: { type: 3 }
      });
    },
    toDel(row) {
      this.$confirm('是否确定删除该订单', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        mengliOrderDel(row.id).then(res => {
          this.$message.success('删除成功');
          this.fetchData();
        }).catch(err => {
          console.error(err);
        });
      }).catch(() => {
        return false;
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.mengli-all-order {
  margin: 20px;
  margin-top: 0px;
  // border:1px solid #eee;
  box-shadow:2px 4px 13px 0px rgba(221,225,234,1);
  border-radius:12px;
  background-color: #fff;
  padding: 24px 24px 10px 24px;
  .order-num {
    color: #406EFF;
  }
}
</style>
